//引入数据加密模块
var bcrypt = require('../dao/bcrypt')
//引入数据模型模块
var dbmodel = require('../model/dbmodule');
//引入token
var jwt = require('../dao/jwt');

//引入数据表模型
var User = dbmodel.model('User');
var Friend = dbmodel.model('Friend');
var Group = dbmodel.model('Group');
var GroupUser = dbmodel.model('GroupUser');
var Message = dbmodel.model('Message');
var GroupMsg = dbmodel.model('GroupMsg');

//新建用户
exports.buildUser = function (name, mail, pwd, res) {
  //密码加密
  var pwd = bcrypt.encryption(pwd);

  //插入数据
  let data = {
    name: name,    //用户名
    psw: pwd,    //密码
    email: mail,    //邮箱
    time: new Date(),    //注册时间
  };

  let user = new User(data);
  user.save(function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200 });
    }
  });
}

//匹配用户名，邮箱
exports.countUserValue = function (data, type, res) {
  let wherestr = {};
  //wherestr = {'type':data};
  wherestr[type] = data;
  User.countDocuments(wherestr, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200, result });
    }
  });
}

//用户验证登录
exports.userMatch = function (data, pwd, res) {
  let wherestr = { $or: [{ 'name': data }, { 'email': data }] };
  let out = { 'name': 1, 'imgurl': 1, 'psw': 1 };
  User.find(wherestr, out, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      if (result == '') {
        res.send({ status: 400 });
      }
      result.map(function (e) {
        const pwdMatch = bcrypt.verification(pwd, e.psw);
        if (pwdMatch) {
          //密码验证成功
          let token = jwt.generateToken(e._id);
          let back = {
            id: e._id,
            name: e.name,
            imgurl: e.imgurl,
            token: token,
          }
          res.send({ status: 200, back });
        } else {
          res.send({ status: 400 });
        }
      });
    }
  });
}

//搜索用户
exports.searchUser = function (data, res) {
  let wherestr = {};
  let out = { 'name': 1, 'imgurl': 1, 'email': 1 };

  if (data == 'admin') {
    wherestr = {};
  } else {
    wherestr = { $or: [{ 'name': { $regex: data } }, { 'email': { $regex: data } }] };
  }
  User.find(wherestr, out, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200, result });
    }
  });
}

//用户匹配（是否为好友）
exports.isFriend = function (uid, fid, res) {
  let wherestr = { 'userID': uid, 'friendID': fid, 'state': 0 };
  Friend.findOne(wherestr, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      if (result) {
        //匹配成功，是好友
        res.send({ status: 200 });
      } else {
        //不是好友
        res.send({ status: 400 });
      }
    }
  });
}

//搜索群
exports.searchGroup = function (data, res) {
  let wherestr = {};
  let out = { 'name': 1, 'imgurl': 1 };

  if (data == 'admin') {
    wherestr = {};
  } else {
    wherestr = { 'name': { $regex: data } };
  }
  Group.find(wherestr, out, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200, result });
    }
  });
}

//判断是否在群内
exports.isInGroup = function (uid, gid, res) {
  let wherestr = { 'userID': uid, 'groupID': gid };
  GroupUser.findOne(wherestr, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      if (result) {
        //匹配成功，是在群内
        res.send({ status: 200 });
      } else {
        //不在群内
        res.send({ status: 400 });
      }
    }
  });
}

//用户详情
exports.userDetail = function (uid, res) {
  let wherestr = { '_id': uid };
  let out = { 'psw': 0 };
  User.findOne(wherestr, out, function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200, result });
    }
  });
}

//用户修改
exports.userUpdate = function (data, res) {
  let updatestr = {};
  //判断是否有密码项
  if (data.pwd != undefined) {
    //有密码，进行匹配
    User.find({ '_id': data.id }, { 'psw': 1 }, function (err, result) {
      if (err) {
        res.send({ status: 500 });
      } else {
        if (result == '') {
          res.send({ status: 400 });
        }
        result.map(function (e) {
          const pwdMatch = bcrypt.verification(data.pwd, e.psw);
          if (pwdMatch) {
            //密码验证成功
            //如果为密码修改，需要先加密
            if (data.type == 'psw') {
              let password = bcrypt.encryption(data.data);
              updatestr[data.type] = password;
            } else {
              //邮箱匹配
              updatestr[data.type] = data.data;
              User.countDocuments(updatestr, function (err, result) {
                if (err) {
                  res.send({ status: 500 });
                } else {
                  if (result == 0) {
                    //没有匹配项，可以修改
                    User.findByIdAndUpdate(data.id, updatestr, function (err, result) {
                      if (err) {
                        // 修改失败
                        res.send({ status: 500 });
                      } else {
                        //修改成功
                        res.send({ status: 200 });
                      }
                    });
                  } else {
                    //已存在
                    res.send({ status: 300 });
                  }
                }
              });
            }

            // res.send({status:200,back});
          } else {
            //密码匹配失败
            res.send({ status: 400 });
          }
        });
      }
    });
  } else if (data.type == 'name') {
    //查找用户名是否重名
    updatestr[data.type] = data.data;
    User.countDocuments(updatestr, function (err, result) {
      if (err) {
        res.send({ status: 500 });
      } else {
        if (result == 0) {
          //没有匹配项，可以修改
          User.findByIdAndUpdate(data.id, updatestr, function (err, result) {
            if (err) {
              // 修改失败
              res.send({ status: 500 });
            } else {
              //修改成功
              res.send({ status: 200 });
            }
          });
        } else {
          //已存在
          res.send({ status: 300 });
        }
      }
    });
  } else {
    //一般项修改
    updatestr[data.type] = data.data;
    User.findByIdAndUpdate(data.id, updatestr, function (err, result) {
      if (err) {
        // 修改失败
        res.send({ status: 500 });
      } else {
        //修改成功
        res.send({ status: 200 });
      }
    });
  }
}

//获取好友昵称
exports.getMarkName = function (data, res) {
  let wherestr = { 'userID': data.uid, 'friendID': data.fid };
  let out = { 'markname': 1 };
  Friend.findOne(wherestr, out, function (err, result) {
    if (err) {
      // 获取失败
      res.send({ status: 500 });
    } else {
      //获取成功
      res.send({ status: 200, result });
    }
  });
}

//好友昵称修改
exports.updateMarkName = function (data, res) {
  let wherestr = { 'userID': data.uid, 'friendID': data.fid };
  let updatestr = { 'markname': data.name };
  Friend.updateOne(wherestr, updatestr, function (err, result) {
    if (err) {
      // 修改失败
      res.send({ status: 500 });
    } else {
      //修改成功
      res.send({ status: 200 });
    }
  });
}

//好友操作
//添加好友
exports.bulidFriend = function(uid,fid,state){
  let data = {
    userID: uid,
    friendID: fid,
    state: state,
    time: new Date(),    //注册时间
    lasttime: new Date(),
  };

  let friend = new Friend(data);
  friend.save(function (err, result) {
    if (err) {
      console.log("ERROR:添加好友出错！");
    } else {
      // res.send({ status: 200 });
      console.log("buildFriend option success!");
    }
  });
}

//最后通信时间
exports.upFriendLastTime = function(data){
  // let wherestr = {'userID':uid,'friendID':fid};
  let wherestr = {$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]};
  let updatestr = {'lasttime':new Date()};
  Friend.updateMany(wherestr,updatestr,function(err,result){
    if (err) {
      // res.send({ status: 500 });
      console.log("ERROR:通信时间修改错误！");
    } else {
      // res.send({ status: 200 });
      console.log("upFriendLastTime option success！")
    }
  });
}

//添加一对一消息
exports.insertMsg = function(uid,fid,msg,type,res){
  let data = {
    userID: uid,
    friendID: fid,
    message:msg,
    types:type,
    time: new Date(),    //注册时间
    state:1,
  };

  let message = new Message(data);
  message.save(function (err, result) {
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200 });
    }
  });
}

//好友申请
exports.applyFriend = function(data,res){
  //是否已申请
  let wherestr = {'userID':data.uid,'friendID':data.fid};
  Friend.countDocuments(wherestr,(err,result)=>{
    if (err) {
      res.send({ status: 500 });
    } else {
      //如果result=0，为初次申请
      if(result == 0){
        this.bulidFriend(data.uid,data.fid,2);
        this.bulidFriend(data.fid,data.uid,1);
      }else{
        //已经申请过好友
        this.upFriendLastTime(data);
        // this.upFriendLastTime(data.uid,data.fid);
        // this.upFriendLastTime(data.fid,data.uid);
        /**
         * 优化,可以只用访问一次数据库
         * let wherestr = {$or:[{'userID':uid,'friendID':fid},{'userID':fid,'friendID':uid}]}
         * */ 
      }
      //添加申请内容
      this.insertMsg(data.uid,data.fid,data.msg,0,res);
    }
  });
}

//更新好友状态
exports.updateFriendState = function(data,res){
  //修改项
  let wherestr = {$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]};
  Friend.updateMany(wherestr,{'state':0},function(err,result){
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200 });
    }
  });
}

//拒绝或删除好友
exports.deleteFriend = function(data,res){
  //修改项
  let wherestr = {$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]};
  Friend.deleteMany(wherestr,function(err,result){
    if (err) {
      res.send({ status: 500 });
    } else {
      res.send({ status: 200 });
    }
  });
}

//按要求获取用户列表
exports.getUsers = function(uid,state,res){
  let query = Friend.find({});
  //查询条件
  query.where({'userID':uid,'state':state});
  //查找Friend 关联user对象
  query.populate('friendID');
  //排序方式,最后通信时间的倒叙排列
  query.sort({'lasttime':-1});
  //查询结果
  query.exec().then((e)=>{
    let result = e.map(function(item){
      return {
        id:item.friendID._id,
        name:item.friendID.name,
        markname:item.markname,
        imgurl:item.friendID.imgurl,
        lasttime:item.lasttime
      }
    });
    // console.log(result);
    res.send({ status:200, result });
  }).catch((err)=>{
    res.send({ status: 500 });
  });
}

//按要求获取一对一消息
exports.getOneMsg = function(data,res){
  let query = Message.findOne({});
  //查询条件
  query.where({$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]});
  //发送时间的倒序
  query.sort({'time':-1});
  //查询结果
  query.exec().then((e)=>{
    let result = {
        message:e.message,
        time:e.time,
        types:e.types,
      };
    // console.log(result);
    res.send({ status:200, result });
  }).catch((err)=>{
    res.send({ status: 500 });
  });
}

//汇总一对一消息未读数
exports.unreadMsg = function(data,res){
  let wherestr = {"userID":data.uid,'friendID':data.fid,'state':1};
  Message.countDocuments(wherestr, (err,result)=>{
    if(err){
      res.send({ status: 500 });
    }else{
      res.send({ status: 200, result });
    }
  });
}

//一对一消息置为已读
exports.updateMsg = function(data,res){
  //修改项的条件
  let wherestr = {"userID":data.uid,'friendID':data.fid,'state':1};
  // 修改内容
  let updatestr = {'state':0};
  Message.updateMany(wherestr, updatestr, (err,result)=>{
    if(err){
      res.send({ status: 500 });
    }else{
      res.send({ status: 200});
    }
  });
}

//按要求获取群列表
exports.getGroup = function(data,res){
  let query = GroupUser.find({});
  //查询条件
  query.where({'userID':data});
  //查找Friend 关联user对象
  query.populate('groupID');
  //排序方式,最后通信时间的倒叙排列
  query.sort({'lasttime':-1});
  //查询结果
  query.exec().then((e)=>{
    let result = e.map(function(item){
      return {
        gid:item.groupID._id,
        name:item.groupID.name,
        markname:item.name,
        imgurl:item.groupID.imgurl,
        lasttime:item.lasttime,
        tip:item.tip,
      }
    });
    // console.log(result);
    res.send({ status:200, result });
  }).catch((err)=>{
    res.send({ status: 500 });
  });
}

//按要求获取群消息
exports.getOneGroupMsg = function(gid,res){
  let query = GroupMsg.findOne({});
  //查询条件
  query.where({'groupID':gid});
  //关联项
  query.populate('userID');
  //发送时间的倒序
  query.sort({'time':-1});
  //查询结果
  query.exec().then((e)=>{
    let result = {
        message:e.message,
        time:e.time,
        types:e.types,
        name:e.userID.name,
      };
    // console.log(result);
    res.send({ status:200, result });
  }).catch((err)=>{
    res.send({ status: 500 });
  });
}

//群消息置为已读
exports.updateGroupMsg = function(data,res){
  //修改项的条件
  let wherestr = {"groupID":data.gid,'userID':data.uid};
  // 修改内容
  let updatestr = {'tip':0};
  GroupUser.updateOne(wherestr, updatestr, (err,result)=>{
    if(err){
      res.send({ status: 500 });
    }else{
      res.send({ status: 200});
    }
  });
}
